﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace oop_5_server
{
    /// <summary>
    /// Packet - пакет ответа.
    /// </summary>
    /// <li>
    /// <lu>В теории должен реализовывать паттерн Composite. Но реализованы только самые необходимые методы.</lu>
    /// </li>
    class Packet : Object
    {
        protected Dictionary<string, Packet> childs;
        protected string value;

        public Packet(string value = "")
        {
            childs = new Dictionary<string, Packet>();
            this.value = value;
        }

        public void Add(string key, Packet value)
        {
            this.childs.Add(key, value);
            return;
        }

        public void Add(string key, string value)
        {
            Packet newchild = new Packet(value);
            this.childs.Add(key, newchild);
            return;
        }

        public int Count
        {
            get { return this.childs.Count; }
        }

        public string CreateJSON()
        {
            string response = "";

            if (this.childs.Count == 0) {
                response += string.Format("\"{0}\" ", value);
                return response;
            }

            response = "{";

            foreach (KeyValuePair<string, Packet> kvp in childs)
            {
                response += string.Format("\"{0}\": {1}, ", kvp.Key, ((Packet)kvp.Value).CreateJSON());
            }

            response += "\"0\": 0 }";

            return response;
        }


    }
}
